package cn.kgc.shiro.shiro;

import cn.kgc.shiro.entity.Role;
import cn.kgc.shiro.entity.User;
import cn.kgc.shiro.entity.UserRole;
import cn.kgc.shiro.mapper.RoleMapper;
import cn.kgc.shiro.mapper.UserMapper;
import cn.kgc.shiro.mapper.UserRoleMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 课工场
 * @date 2023/11/21
 * @description
 *  日志打印      log.debug   log.info    log.warn  log.error
 *     debug   info   warn   error
 *
 */
@Slf4j
public class CustomerRealm extends AuthorizingRealm {

    @Resource
    private UserMapper userMapper;

    @Resource
    private UserRoleMapper  userRoleMapper;

    @Resource
    private RoleMapper roleMapper;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {


         log.debug("--------------doGetAuthorizationInfo-----------------");

        // 根据用户身份信息查询数据库
        String primaryPrincipal = (String) principals.getPrimaryPrincipal();
        LambdaQueryWrapper<User> lambda = new QueryWrapper<User>().lambda();
        lambda.eq(User::getUsername,primaryPrincipal);
        User user = userMapper.selectOne(lambda);
        Integer uid = user.getId();

        // 根据用户id  查询用户角色id   user_role
        LambdaQueryWrapper<UserRole> lambda1 = new QueryWrapper<UserRole>().lambda();
        lambda1.eq(UserRole::getUserId,uid);
        List<UserRole> userRoles = userRoleMapper.selectList(lambda1);

        // 遍历集合 获取 角色id
        List<Integer> rids = userRoles.stream().map(userRole -> userRole.getRoleId()).collect(Collectors.toList());

        //  根据角色id  查询用户的角色标识符
        LambdaQueryWrapper<Role> lambda2 = new QueryWrapper<Role>().lambda();
        lambda2.in(Role::getRoleId,rids);
        List<String> roleNames = roleMapper.selectList(lambda2).stream().map(role -> role.getRoleName()).collect(Collectors.toList());

        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addRoles(roleNames);

        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        log.debug("--------------doGetAuthenticationInfo-----------------");

        UsernamePasswordToken usernamePasswordToken  = (UsernamePasswordToken) token;
        String username = usernamePasswordToken.getUsername();
        char[] password = usernamePasswordToken.getPassword();
        String pwd = new String(password);

        log.debug("username={},password={}",username,pwd);

        // 根据用户名查询用户信息
        LambdaQueryWrapper<User> lambda = new QueryWrapper<User>().lambda();
        lambda.eq(User::getUsername,username);
        User user = userMapper.selectOne(lambda);

        if (ObjectUtils.isNotNull(user)){
            SimpleAuthenticationInfo simpleAuthenticationInfo =
                    new SimpleAuthenticationInfo(user.getUsername(),user.getPassword(),
                            ByteSource.Util.bytes(user.getSalt()),this.getName());
            return simpleAuthenticationInfo;
        }
        return null;
    }
}
